package com.igeek.ch01;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Servlet本质上是一个Java类，遵循extends HttpServlet
 * 可以接收处理请求，并响应
 *
 * @WebServlet 注解标注的类，说明此类是一个Servlet类
 * 1.name属性：标识，当前Servlet的名字
 * 2.urlPatterns属性、value属性：当前Servlet能够处理的请求，必须添加 /xxx
 * 3.loadOnStartup属性：决定Servlet的实例化初始化顺序；随着Tomcat的启动，而实例化和初始化Servlet，且正数值越小越先启动
 * 4.initParams属性：初始化参数，而且可以配置多个 {}
 *
 * @WebInitParam 注解，初始化参数
 * 1.name属性：key键
 * 2.value属性：value值
 *
 * Servlet的生命周期
 * 1.先正常启动Tomcat
 * 2.访问Servlet时，才会实例化、初始化，有且仅会实例化初始化一次
 * 3.根据访问方式，来调用doGet()、doPost()
 * 4.关闭Tomcat，销毁
 *
 */
@WebServlet(name = "FirstServlet" , urlPatterns ={"/first","/firstServlet"} ,loadOnStartup = 2 ,
        initParams = {@WebInitParam(name="version",value="1.0") , @WebInitParam(name="start",value = "20")})
public class FirstServlet extends HttpServlet {

    public FirstServlet(){
        System.out.println("FirstServlet() 实例化");
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //初始化时，读取当前Servlet的初始化参数
        String version = config.getInitParameter("version");
        String start = config.getInitParameter("start");
        System.out.println("FirstServlet init() 初始化" + version + start);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doPost");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doGet");
    }

    @Override
    public void destroy() {
        System.out.println("FirstServlet destroy() 销毁");
    }

}
